package com.example.a_java.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.a_java.dto.RepaymentRecordDTO;
import com.example.a_java.entity.LoanContract;
import com.example.a_java.entity.LoanRepaymentPlan;
import com.example.a_java.entity.LoanRepaymentRecord;
import com.example.a_java.mapper.LoanContractMapper;
import com.example.a_java.mapper.LoanRepaymentPlanMapper;
import com.example.a_java.mapper.LoanRepaymentRecordMapper;
import com.example.a_java.service.RepaymentRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 还款记录Service实现�?
 */
@Service
@Slf4j
public class RepaymentRecordServiceImpl extends ServiceImpl<LoanRepaymentRecordMapper, LoanRepaymentRecord> implements RepaymentRecordService {

    @Autowired
    private LoanRepaymentRecordMapper repaymentRecordMapper;

    @Autowired
    private LoanRepaymentPlanMapper repaymentPlanMapper;

    @Autowired
    private LoanContractMapper contractMapper;

    @Override
    public IPage<Map<String, Object>> getRepaymentRecordList(Page<LoanRepaymentRecord> page, 
                                                          String loanNo, 
                                                          String contractNo, 
                                                          String customerName, 
                                                          String payMethod, 
                                                          String startDate, 
                                                          String endDate) {
        return repaymentRecordMapper.selectRepaymentRecordList(page, loanNo, contractNo, customerName, payMethod, startDate, endDate);
    }

    @Override
    public Map<String, Object> getRepaymentRecordDetail(Long recordId) {
        return repaymentRecordMapper.selectRepaymentRecordDetail(recordId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> recordRepayment(RepaymentRecordDTO recordDTO) {
        Map<String, Object> result = new HashMap<>();
        
        // 1. 查询还款计划
        LoanRepaymentPlan plan = repaymentPlanMapper.selectById(recordDTO.getPlanId());
        if (plan == null) {
            throw new RuntimeException("还款计划不存在");
        }
        
        // 2. 查询合同信息
        LoanContract contract = contractMapper.selectById(recordDTO.getContractId());
        if (contract == null) {
            throw new RuntimeException("合同信息不存在");
        }
        
        // 3. 创建还款记录
        LoanRepaymentRecord record = new LoanRepaymentRecord();
        record.setContractId(recordDTO.getContractId());
        record.setPlanId(recordDTO.getPlanId());
        record.setRepayAmount(recordDTO.getPayAmount());
        record.setPrincipal(recordDTO.getPrincipal());
        record.setInterest(recordDTO.getInterest());
        record.setPenalty(recordDTO.getPenalty() != null ? recordDTO.getPenalty() : BigDecimal.ZERO);
        record.setRepayMethod(Integer.parseInt(recordDTO.getPayMethod()));
        record.setTransactionNo(recordDTO.getTransactionNo());
        record.setRemark(recordDTO.getRemark());
        record.setRepayTime(LocalDateTime.parse(recordDTO.getPayDate() + " 00:00:00", 
                           DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        record.setCreateTime(LocalDateTime.now());
        record.setIsDeleted(0);
        
        // 4. 保存还款记录
        repaymentRecordMapper.insert(record);
        
        // 5. 更新还款计划状态
        plan.setRepayStatus(20); // 已还款状态
        plan.setUpdateTime(LocalDateTime.now());
        repaymentPlanMapper.updateById(plan);
        
        // 6. 获取剩余本金并返回结果
        BigDecimal remainingPrincipal = plan.getPrincipalBalance();
        
        // 7. 返回结果
        result.put("recordId", record.getRecordId());
        result.put("remainingPrincipal", remainingPrincipal);
        
        return result;
    }
} 
